package com.generic.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.generic.dao.impl.MemberDao;
import com.generic.ds.HibernateSession;
import com.generic.module.impl.Member;
import com.generic.util.Constant;
import com.generic.util.Encoder;
import com.opensymphony.xwork2.ActionSupport;

public class AccountActivation extends ActionSupport {
	
	private static final long serialVersionUID = 6329248941565363326L;
	
	private String a;
	private String k;
	
	public String getA() {
		return a;
	}

	public String getK() {
		return k;
	}

	public void setA(String a) {
		this.a = a;
	}

	public void setK(String k) {
		this.k = k;
	}

	@Action(value = "/account-activation", results = { 
			@Result(name = "error", location="ajax-error.jsp"), 
			@Result(name = "success", type="redirectAction", params={"actionName","home"}) })
	public String execute() {
		String result = SUCCESS;
		HibernateSession hs = new HibernateSession();
		try {
			String account = Encoder.decode(a);
			if(account != null && k != null) {
				hs.beginTransaction();
				MemberDao memberDao = new MemberDao(hs);
				Member member = (Member)memberDao.find("email", account);
				if(member.getActivationKey().equals(k)) {
					member.setStatus(Constant.ACCOUNT_ACTIVE);
				} else {
					throw new Exception("Invalid activation key");
				}
				hs.commitTransaction();
				addActionMessage("Account activated");
			} else {
				throw new Exception("Missing account and/or activation key");
			}
		} catch (Exception e) {
			hs.rollbackTransaction(e);
			addActionError("Account activation failed");
			result = ERROR;
		} finally {
			hs.closeSession();
		}

		return result;
	}
}
